<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RunJS</title>
<!-- base -->
<link rel="stylesheet" href="/assets/lib/bootstrap/css/bootstrap.min.css" />
<script src="/assets/lib/jquery/2.1.4/jquery-2.1.4.min.js"></script>
<script src="/assets/lib/bootstrap/js/bootstrap.min.js"></script>

<!-- codemirror -->
<link rel="stylesheet" href="/assets/lib/codemirror/lib/codemirror.css">
<script src="/assets/lib/codemirror/lib/codemirror.js"></script>

<!-- htmlmixed -->
<script src="/assets/lib/codemirror/mode/xml/xml.js"></script>
<script src="/assets/lib/codemirror/mode/javascript/javascript.js"></script>
<script src="/assets/lib/codemirror/mode/css/css.js"></script>
<script src="/assets/lib/codemirror/mode/vbscript/vbscript.js"></script>
<script src="/assets/lib/codemirror/mode/htmlmixed/htmlmixed.js"></script>
<script src="/assets/lib/codemirror/addon/selection/selection-pointer.js"></script>

<!-- sublime -->
<link rel="stylesheet" href="/assets/lib/codemirror/doc/docs.css">
<link rel="stylesheet" href="/assets/lib/codemirror/addon/fold/foldgutter.css">
<link rel="stylesheet" href="/assets/lib/codemirror/addon/dialog/dialog.css">
<script src="/assets/lib/codemirror/addon/search/searchcursor.js"></script>
<script src="/assets/lib/codemirror/addon/search/search.js"></script>
<script src="/assets/lib/codemirror/addon/dialog/dialog.js"></script>
<script src="/assets/lib/codemirror/addon/edit/matchbrackets.js"></script>
<script src="/assets/lib/codemirror/addon/edit/closebrackets.js"></script>
<script src="/assets/lib/codemirror/addon/comment/comment.js"></script>
<script src="/assets/lib/codemirror/addon/wrap/hardwrap.js"></script>
<script src="/assets/lib/codemirror/addon/fold/foldcode.js"></script>
<script src="/assets/lib/codemirror/addon/fold/brace-fold.js"></script>
<script src="/assets/lib/codemirror/keymap/sublime.js"></script>

<!-- xmlcomplete -->
<link rel="stylesheet" href="/assets/lib/codemirror/addon/hint/show-hint.css">
<script src="/assets/lib/codemirror/addon/hint/show-hint.js"></script>
<script src="/assets/lib/codemirror/addon/hint/xml-hint.js"></script>

<!-- match tag -->
<script src="/assets/lib/codemirror/addon/fold/xml-fold.js"></script>
<script src="/assets/lib/codemirror/addon/edit/matchtags.js"></script>

<!-- highlight -->
<script src="/assets/lib/codemirror/addon/search/searchcursor.js"></script>
<script src="/assets/lib/codemirror/addon/search/match-highlighter.js"></script>
<style>
.top {
  border-bottom: 1px solid #C0C0C0;
  position: fixed;
  height: 60px;
  width: 100%;
  background-color: rgba(0,0,0,0.1);
  z-index: 1000;
}

.content {
  padding-top: 60px; 
}
.padding {
  padding: 10px;
}

.CodeMirror {
  border: 1px solid #eee;
  height: 100%;
  font-family: Monaco, Consolas, monospace;
}

.CodeMirror-focused .cm-matchhighlight {
  border-bottom: 2px solid #00ff8f;
}

.row {
  margin-left: 0;
  margin-right: 0;
}

.col-lg-1, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-md-1, .col-md-10, .col-md-11, .col-md-12, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-sm-1, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-xs-1, .col-xs-10, .col-xs-11, .col-xs-12, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9 {
  padding-left: 0;
  padding-right: 0;
}

ul.menu {
  list-style: outside none none;
  margin: 0;
  padding: 0;
}
ul.menu li {
  position: relative;
  margin-bottom: 5px;
}
ul.menu li a {
  transition: all 0.2s ease 0s;
  border-left: 0px solid #080;
  padding: 6px 10px;
  color: #000;
  display: block;
  background: #eee;
}
ul.menu li a:hover {
  border-left: 5px solid #080;
  color: #080;
  background: #ddd;
}
ul.menu li .menu-btn-gp {
  position: absolute;
  right: 0;
  top: 0;
  padding: 5px 0;
}
.menu-btn-gp button {
  margin-right: 5px;
  font-size: 9px;
  line-height: normal;
}
</style>
</head>
<body>

<div class="top">
  <div class="row">
    <div class="col-md-10 col-md-offset-2">
      <div class="padding">
        <button id="run" class="btn btn-primary">运行</button>
      </div>
    </div>
  </div>
</div>
<div class="content">
  <div class="row">
    <div class="col-md-2">
      <div class="form-horizonal padding">
        <form action="#">
          <fieldset>
<!--           <div>
            <textarea style="resize:none;" rows="3" id="" placeholder="css or js"></textarea>
          </div>
          <button class="btn btn-primary btn-block btn-large" id="addResource">添加</button> -->
          <button class="btn btn-danger" id="reset">还原</button>
          <button class="btn btn-primary" id="store">保存</button>
          </fieldset>
        </form>
      </div>
      <ul class="menu" id="action"></ul>
    </div>
    <div class="col-md-10 row">
      <div class="col-md-6 full-height">
        <textarea id="code" name="code"></textarea>
      </div>
      <div class="col-md-6 full-height">
        <iframe id="preview" style="border:0;width:100%;height:100%"></iframe>
      </div>
    </div>
  </div>
</div>
<div class="bottom"></div>
<script type="text/javascript">
(function() {
var myCodeMirror, delay, template = "";

var dummy = {
  attrs: {
    color: ["red", "green", "blue", "purple", "white", "black", "yellow"],
    size: ["large", "medium", "small"],
    description: null
  },
  children: []
};

var tags = {
  "!top": ["top"],
  "!attrs": {
    id: null,
    class: ["A", "B", "C"]
  },
  top: {
    attrs: {
      lang: ["en", "de", "fr", "nl"],
      freeform: null
    },
    children: ["animal", "plant"]
  },
  animal: {
    attrs: {
      name: null,
      isduck: ["yes", "no"]
    },
    children: ["wings", "feet", "body", "head", "tail"]
  },
  plant: {
    attrs: {name: null},
    children: ["leaves", "stem", "flowers"]
  },
  wings: dummy, feet: dummy, body: dummy, head: dummy, tail: dummy,
  leaves: dummy, stem: dummy, flowers: dummy
};

function completeAfter(cm, pred) {
  var cur = cm.getCursor();
  if (!pred || pred()) setTimeout(function() {
    if (!cm.state.completionActive)
      cm.showHint({completeSingle: false});
  }, 100);
  return CodeMirror.Pass;
}

function completeIfAfterLt(cm) {
  return completeAfter(cm, function() {
    var cur = cm.getCursor();
    return cm.getRange(CodeMirror.Pos(cur.line, cur.ch - 1), cur) == "<";
  });
}

function completeIfInTag(cm) {
  return completeAfter(cm, function() {
    var tok = cm.getTokenAt(cm.getCursor());
    if (tok.type == "string" && (!/['"]/.test(tok.string.charAt(tok.string.length - 1)) || tok.string.length == 1)) return false;
    var inner = CodeMirror.innerMode(cm.getMode(), tok.state).state;
    return inner.tagName;
  });
}

$.ajax("../ubus-menu.t/index.html", {
  success: function(data) {
    template = data;
  }
});

function updatePreview() {
  var dpreview = document.getElementById("preview");
  var ddocument = dpreview.contentDocument || dpreview.contentWindow.document;
  ddocument.open();
  var body = myCodeMirror.getValue()
  body += '<link rel="stylesheet" href="/assets/css/example.css" />'
  ddocument.write(body);
  ddocument.close();
}

myCodeMirror = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  mode: "htmlmixed",
  viewportMargin: Infinity,
  keyMap: "sublime",
  autoCloseBrackets: true,
  matchBrackets: true,
  showCursorWhenSelecting: true,
  extraKeys: {
    "'<'": completeAfter,
    "'/'": completeIfAfterLt,
    "' '": completeIfInTag,
    "'='": completeIfInTag,
    "Ctrl-Space": "autocomplete",
    "Ctrl-J": "toMatchingTag"
  },
  hintOptions: {schemaInfo: tags},
  matchTags: {bothTags: true},
  highlightSelectionMatches: {showToken: /\w/}
});

// myCodeMirror.on("change", function() {
//   clearTimeout(delay);
//   delay = setTimeout(updatePreview, 1000);
// });

$("#run").click(function() {
  updatePreview();
});

$("#reset").click(function() {
  _confirm('确认还原？', function(){myCodeMirror.setValue(template)});
});


function localStore(key) {
  var data = localStorage[key];

  if (data)
  {
    try {
      data = JSON.parse(data);
    } catch (e) {

    }
  }

  return {
    add: function(val) {
      if (typeof data != 'object')
      {
        data = [];
      }
      data.push(val);
      localStorage[key] = JSON.stringify(data);
    },
    update: function(index, val) {
      if (data && data.length > 0)
      {
        data[index] = val;
        localStorage[key] = JSON.stringify(data);
      }
    },
    remove: function(index)
    {
      if (data && data.length > 0)
      {
        data.splice(index, 1);
        localStorage[key] = JSON.stringify(data);
      }
    },
    get: function(index) {
      return data[index];
    },
    size: function() {
      return (data ? data.length : 0);
    }
  }
}

var runjsCodes = localStore('runjsCodes');

function createButton(index) {
  // $('<button>').text(runjsCodes.get(index).name).click(function() {
  //   restoreCode(index);
  // }).addClass('btn btn-small').appendTo('#action');
  $('<li>').append($('<a href="javascript:;">').text(runjsCodes.get(index).name).attr('title', runjsCodes.get(index).name).click(function() {
    restoreCode(index);
  })).append(
    $('<div class="menu-btn-gp">')
      .append($('<button class="btn btn-warning btn-xs">更新</button>').click(function() {
        _confirm('确认更新？',function(){saveCode(index);});
      })).append($('<button class="btn btn-danger btn-xs">删除</button>').click(function() {
        _confirm('确认删除？',function(){removeCode(index);});
      }))
  ).data('id', index).appendTo('#action');
}

function _confirm(text, cb) {
  var isConfirmed = confirm(text);
  if (isConfirmed)
    cb();
}

function restoreCode(index) {
  myCodeMirror.setValue(runjsCodes.get(index).code);
}

function saveCode(index) {
  runjsCodes.update(index, {
    name: runjsCodes.get(index).name,
    code: myCodeMirror.getValue()
  });
}

function removeCode(index) {
  runjsCodes.remove(index);
  $("#action").find('li').each(function() {
    if ($(this).data('id') == index)
    {
      $(this).remove();
      return false;
    }
  })
}

$("#store").click(function() {
  var name = prompt("请指定一个保存名称");
  if (!name)
    return;
  //save code
  runjsCodes.add({
    name: name,
    code: myCodeMirror.getValue()
  });
  //create button
  createButton(runjsCodes.size() - 1);
})


function init() {
  var size = runjsCodes.size();
  if (size > 0)
  {
    for (var i = 0; i < size; i++)
    {
      createButton(i);
    }
  }
}

init();

if (localStorage.cacheCode != undefined)
  myCodeMirror.setValue(localStorage.cacheCode);

setInterval(function() {
  localStorage.cacheCode = myCodeMirror.getValue();
},1000);

$('.full-height').height($(window).height()-70);

}());
</script>
</body>
</html>